#------------------------------------------------------------------
#
# Name:         list.py
# 
# Author:       Dragon@Dragon Technology Co.,Ltd
#
# Created:      Apr 23th,2008
# 
# CopyRight:    (c) 2008-2010 dragon
#
# Licence:      BSD Licence 
#
#------------------------------------------------------------------

import os
from os import *
from string import *
import codecs
import xml.dom.minidom

#------------------------------------------------------------------
# defination intenal vailabe, global vailabe and so on 
#------------------------------------------------------------------

media_type=['mp3','MP3','mpg','MPG',
            'mp4','MP4','ogg','OGG',
            'wma','WMA','mov','MOV',
            'asf','ASF','avi','AVI']

#------------------------------------------------------------------
# get home directory of current login user (windows,unix,mac)
#------------------------------------------------------------------

def get_home_dir():
    try:
        path1=os.path.expanduser("~")
    except:
        path1=""
    try:
        path2=os.environ["HOME"]
    except:
        path2=""
    try:
        path3=os.environ["USERPROFILE"]
    except:
        path3=""
        
    if not os.path.exists(path1):
        if not os.path.exists(path2):
            if not os.path.exists(path3):
                return os.getcwd()
            else: return path3
        else: return path2
    else: return path1

#------------------------------------------------------------------
# This class is used to build xml configure file
#------------------------------------------------------------------
class writedata():
    def __init__(self,conf_file_name):
        home_dir = get_home_dir()
        list_path = os.path.join(home_dir,'.dolphin')
        if not os.path.isdir(list_path):
            os.mkdir(list_path)   

        fp = file(os.path.join(list_path,conf_file_name), 'wb')
        self.fp = fp

        self.init_write()
    
    def __exit__(self):
        self.fp.close()

#------------------------------------------------------------------

    def init_write(self):          
        impl = xml.dom.minidom.getDOMImplementation()
        dom = impl.createDocument(None, 'list', None)
        root = dom.documentElement
        self.dom = dom
        self.root = root

    def split_media_file(self,filename):
        name = split(filename,'.')[-1]
        for m_index in media_type:
            if name == m_index:
                return name
        return None
    
    def add_record(self,path):
        m_list = self.dom.createElement('record')
        url = self.dom.createTextNode(path)
        m_list.appendChild(url);
        
        m_list.setAttribute("alias",os.path.basename(path))
        return m_list


    def get_list(self,dirname):
        if not dirname==None:
            for root,dirs,files in os.walk(dirname):
                for name in files:
                    if not os.path.isdir(os.path.join(root,name)):
                        if not self.split_media_file(name) == None:
                            rows = self.add_record(os.path.join(root,name))
                            self.root.appendChild(rows)
                            
    def write_data_in(self,targetdir):        
        self.get_list(targetdir)
        self.root.toprettyxml()
        
        writer = codecs.lookup('utf-8')[3](self.fp)
        self.dom.writexml(writer,encoding='utf-8')
        writer.close()

#------------------------------------------------------------------


#------------------------------------------------------------------
# This class is used to read value from xml configure file
#------------------------------------------------------------------
class readdata():
    def __init__(self,conf_file_name):
        self.init_read(conf_file_name)

#------------------------------------------------------------------

    def init_read(self,conf_file_name): 
        home_dir = get_home_dir()
        list_path = os.path.join(home_dir,'.dolphin')
        if os.path.isfile(
            os.path.join(list_path,conf_file_name)):
            if os.path.getsize(
                os.path.join(list_path,conf_file_name)) > 0: 
                rdom = xml.dom.minidom.parse(
                    os.path.join(list_path,conf_file_name))
                r_root = rdom.documentElement
                self.r_root = r_root
            else:
                self.r_root=None
        else:
            self.r_root=None

#------------------------------------------------------------------
        
    def get_record(self,root,tag,attr,attr_value):
        node = root.getElementsByTagName(tag)    
        for list_node in node:
            if list_node.nodeType == list_node.ELEMENT_NODE:
                if list_node.getAttribute(attr) == attr_value:
                    return list_node

#------------------------------------------------------------------

    def get_fullname(self,alias):
        if not self.r_root == None:
            node = self.get_record(self.r_root,'record','alias',alias)
            for item in node.childNodes:
                if item.nodeType == item.TEXT_NODE:
                    return strip(item.data,chars=None)
        else:
            return "Don't find any data file"
        
#------------------------------------------------------------------

    def get_name_list(self):
        name_list=[]
        if not self.r_root == None:
            for node in self.r_root.childNodes:
                if node.nodeType == node.ELEMENT_NODE:        
                    name = node.getAttribute('alias')
                    name_list.append(name)                    
        else:
            print "No find data file"
        return name_list

#------------------------------------------------------------------
